package com.yuanye.yeecho.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class YY {

    public static final String tag = "YY_Util";

    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);

    @SuppressLint("SimpleDateFormat")
    public static String formatTime(long time, String format){
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Date date = new Date(time);
        return formatter.format(date);
    }

    public static String execShell(String cmd){
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return execShell(p);
    }

    public static String execShell(String[] cmds){
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(cmds);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return execShell(p);
    }

    public static String execShell(Process process){
        String result = "";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
            result = builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return result.trim();
    }

    public static String randomString(int length) {
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(characters.charAt(random.nextInt(characters.length())));
        }
        return sb.toString();
    }

    public static String getAppVersion(Context context){
        String currentVersionName = "";
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
//            int currentVersionCode = packageInfo.versionCode;
            currentVersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return currentVersionName;
    }

}
